package logic

import (
	"context"
	"errors"
	"srv/cache"
	"srv/models"

	"srv/house"
	"srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *house.UserLoginRequest) (*house.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(context.Background(), "sendSms"+in.Phone+"Login").Val()
	if get != in.Code {
		incr := cache.Rdb.Incr(context.Background(), "err_login_incr").Val()
		if incr >= 5 {
			cache.Rdb.Del(context.Background(), "sendSms"+in.Phone+"Login")
			cache.Rdb.Del(context.Background(), "sendSms"+in.Phone+"Login")
			logx.Error("验证码错误次数超过5次,请重新申请")
			return nil, errors.New("验证码错误次数超过5次,请重新申请")
		}
		logx.Error("验证码错误")
		return nil, errors.New("验证码错误")
	}
	var newUser models.User
	newUser.FindUser(in.Phone)
	if newUser.ID == 0 {
		newUser.Phone = in.Phone
		newUser.CreateUser()
	}
	cache.Rdb.Del(context.Background(), "sendSms"+in.Phone+"Login")
	cache.Rdb.Del(context.Background(), "sendSms"+in.Phone+"Login")
	return &house.UserLoginResponse{
		UserId: int64(newUser.ID),
	}, nil
}
